package com.avic.map.controller;

import com.avic.map.common.constant.AppConstant;
import com.avic.map.common.constant.LocalResourceConstant;
import com.avic.map.common.constant.SystemLogConstant;
import com.avic.map.common.constant.UserConstant;
import com.avic.map.common.convertor.EmergencyConvertor;
import com.avic.map.common.model.enums.MapDataStatusEnums;
import com.avic.map.common.model.enums.MapTaggingEnums;
import com.avic.map.common.util.AssertUtil;
import com.avic.map.common.util.ex.BizErrorCode;
import com.avic.map.common.util.lang.BaseResponse;
import com.avic.map.common.util.lang.ServiceCallBack;
import com.avic.map.controller.info.EmergencyCarInfo;
import com.avic.map.controller.info.EmergencySoldierInfo;
import com.avic.map.controller.info.EmergencyTaggingInfo;
import com.avic.map.controller.request.AddEmergencyCarReq;
import com.avic.map.controller.request.AddEmergencySoldierReq;
import com.avic.map.controller.request.EmergencyListReq;
import com.avic.map.controller.request.MapEmergencyEndReq;
import com.avic.map.controller.request.MapEmergencyStartReq;
import com.avic.map.controller.request.RemoveEmergencyCarReq;
import com.avic.map.controller.request.RemoveEmergencySoldierReq;
import com.avic.map.controller.request.UpdateEmergencyRecordReq;
import com.avic.map.controller.result.EmergencyListRes;
import com.avic.map.controller.result.GetEmergencyDetailRes;
import com.avic.map.controller.result.GetEmergencyStateRes;
import com.avic.map.controller.result.MapEmergencyEndRes;
import com.avic.map.controller.result.MapEmergencyStartRes;
import com.avic.map.dal.condition.EmergencyListCondition;
import com.avic.map.dal.model.Emergency;
import com.avic.map.dal.model.EmergencyCar;
import com.avic.map.dal.model.EmergencySoldier;
import com.avic.map.dal.model.EmergencyTagging;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author huangsheng
 * @Date 2018/10/23 10:09
 */
@Slf4j
@RestController
@RequestMapping("/emergency")
@Api(tags = "应急相关接口", description = "启动应急&结束应急等")
public class EmergencyController extends AbstractFacadeImpl {

    @ApiOperation(value = "启动应急", notes = "启动应急，修改应急的车辆、船舶和单兵的状，记录应急数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mapEmergencyStartReq", required = true, dataType = "MapEmergencyStartReq"),
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
    })
    @PostMapping("start")
    public MapEmergencyStartRes mapEmergencyStart(@RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId,
                                                  @RequestBody MapEmergencyStartReq mapEmergencyStartReq) {
        log.info("应急启动--mapEmergencyStartReq");
        final MapEmergencyStartRes result = new MapEmergencyStartRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {

            @Override
            public void check() throws Exception {
                AssertUtil.isTrue(null == LocalResourceConstant.EMERGENCY || LocalResourceConstant.EMERGENCY.size() == 0
                        , BizErrorCode.EMERGENCY_IS_EXIST, "当前正在应急，请稍后重试");
                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
            }

            @Override
            public void doService() throws Exception {
                // 记录车辆应急资源
                emergencyService.emergencyStartUpdateMapCarResourceState(mapEmergencyStartReq.getCarNumberS());
                // 记录船舶应急资源
//                emergencyService.emergencyStartUpdateMapShipResourceState(mapEmergencyStartReq.getShipNumbers());
                // 记录单兵应急资源
                emergencyService.emergencyStartUpdateMapSoldierResourceState(mapEmergencyStartReq.getSoldierNumbers());

                log.info("用户 {} 创建了应急");
                String recordId = emergencyService.createEmergency(currentUserId);
                LocalResourceConstant.EMERGENCY_ID = recordId;
                log.info("生成应急数据ID {}", recordId);
                result.setRecordId(recordId);

                // 更新本地缓存
                Emergency emergency = new Emergency();
                emergency.setId(recordId);
                emergency.setCreateUserId(currentUserId);
                emergency.setStartTime(String.valueOf(System.currentTimeMillis()));

                LocalResourceConstant.EMERGENCY.put(currentUserId, emergency);

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.MAP_EMERGENCY_START,
                                null != mapEmergencyStartReq.getCarNumberS() ? mapEmergencyStartReq.getCarNumberS().toString() : "[]",
                                null != mapEmergencyStartReq.getSoldierNumbers() ? mapEmergencyStartReq.getSoldierNumbers().toString() : "[]", recordId), currentUserId);
                result.setSuccess(true);
            }
        });
    }


//    @ApiOperation(value = "添加船舶应急", notes = "启动应急，单量船舶添加应急")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "addEmergencyShipReq", required = true, dataType = "AddEmergencyShipReq"),
//            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
//    })
//    @PutMapping("ship/add")
//    public BaseResponse mapEmergencyShipAdd(@RequestBody AddEmergencyShipReq addEmergencyShipReq,
//                                            @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
//        log.info("添加船舶应急--mapEmergencyStartReq");
//        final BaseResponse result = new BaseResponse();
//        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
//
//            @Override
//            public void check() throws Exception {
//                AssertUtil.isNotBlank(currentUserId, "用户不能为空");
//                AssertUtil.isTrue(addEmergencyShipReq.getNumber() > 0, BizErrorCode.PARAM_ERROR, "船舶编号不存在");
//                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.size() > 0, BizErrorCode.PARAM_ERROR, "当前未应急，不能操作");
//                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.containsKey(currentUserId), BizErrorCode.PARAM_ERROR, "您不是应急发起人，不能操作");
//                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
//            }
//
//            @Override
//            public void doService() throws Exception {
//                // 记录船舶应急资源
////                emergencyService.emergencyStartUpdateMapShipResourceState(addEmergencyShipReq.getNumber(), MapDataStatusEnums.JOIN.getType());
//                // 新建系统日志
//                systemServiceFeignService.createSystemLog(
//                        String.format(SystemLogConstant.ADD_SHIP_MAP_EMERGENCY, addEmergencyShipReq.getNumber(), LocalResourceConstant.EMERGENCY_ID), currentUserId);
//                result.setSuccess(true);
//            }
//        });
//    }

//    @ApiOperation(value = "移除船舶应急", notes = "移除船舶应急，单量船舶移除应急")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "removeEmergencyShipReq", required = true, dataType = "RemoveEmergencyShipReq"),
//            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
//    })
//    @PutMapping("ship/remove")
//    public BaseResponse mapEmergencyShipRemove(@RequestBody RemoveEmergencyShipReq removeEmergencyShipReq,
//                                               @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
//        log.info("添加船舶应急--mapEmergencyStartReq");
//        final BaseResponse result = new BaseResponse();
//        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
//
//            @Override
//            public void check() throws Exception {
//                AssertUtil.isNotBlank(currentUserId, "用户不能为空");
//                AssertUtil.isTrue(removeEmergencyShipReq.getNumber() > 0, BizErrorCode.PARAM_ERROR, "船舶编号不存在");
//                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.size() > 0, BizErrorCode.PARAM_ERROR, "当前未应急，不能操作");
//                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.containsKey(currentUserId), BizErrorCode.PARAM_ERROR, "您不是应急发起人，不能操作");
//                AssertUtil.isNotBlank(currentUserId, "操作人不能为空");
//            }
//
//            @Override
//            public void doService() throws Exception {
//                // 记录船舶应急资源
////                emergencyService.emergencyStartUpdateMapShipResourceState(removeEmergencyShipReq.getNumber(), MapDataStatusEnums.SIGN.getType());
////
//                // 新建系统日志
//                systemServiceFeignService.createSystemLog(
//                        String.format(SystemLogConstant.REMOVE_SHIP_MAP_EMERGENCY, removeEmergencyShipReq.getNumber(), LocalResourceConstant.EMERGENCY_ID), currentUserId);
//                result.setSuccess(true);
//            }
//        });
//    }

    @ApiOperation(value = "添加车辆应急", notes = "启动应急，单量车辆应急")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "addEmergencyShipReq", required = true, dataType = "AddEmergencyCarReq"),
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
    })
    @PutMapping("car/add")
    public BaseResponse mapEmergencyCarAdd(@RequestBody AddEmergencyCarReq addEmergencyCarReq,
                                           @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("添加车辆应急--mapEmergencyCarAdd");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {

            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(currentUserId, "用户不能为空 ");
                AssertUtil.isNotBlank(addEmergencyCarReq.getNumber(), "车辆编号不能为空 ");
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.size() > 0, BizErrorCode.PARAM_ERROR, "当前未应急，不能操作");
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.containsKey(currentUserId), BizErrorCode.PARAM_ERROR, "您不是应急发起人，不能操作");
            }

            @Override
            public void doService() throws Exception {
                // 记录船舶应急资源
                emergencyService.emergencyStartUpdateMapCarResourceState(addEmergencyCarReq.getNumber(), MapDataStatusEnums.CAR_ONLINE_EMERGENCY.getType());

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.ADD_CAR_MAP_EMERGENCY, addEmergencyCarReq.getNumber(), LocalResourceConstant.EMERGENCY_ID), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "移除车辆应急", notes = "移除船舶应急，单量船舶移除应急")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "removeEmergencyCarReq", required = true, dataType = "RemoveEmergencyCarReq"),
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
    })
    @PutMapping("car/remove")
    public BaseResponse mapEmergencyCarRemove(@RequestBody RemoveEmergencyCarReq removeEmergencyCarReq,
                                              @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("添加船舶应急--mapEmergencyStartReq");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {

            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(currentUserId, "用户不能为空");
                AssertUtil.isNotBlank(removeEmergencyCarReq.getNumber(), "船舶编号不存在");
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.size() > 0, BizErrorCode.PARAM_ERROR, "当前未应急，不能操作");
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.containsKey(currentUserId), BizErrorCode.PARAM_ERROR, "您不是应急发起人，不能操作");
            }

            @Override
            public void doService() throws Exception {
                // 记录车辆应急资源
                emergencyService.emergencyStartUpdateMapCarResourceState(removeEmergencyCarReq.getNumber(), MapDataStatusEnums.CAR_OFFLINE_EMERGENCY.getType());

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.REMOVE_CAR_MAP_EMERGENCY, removeEmergencyCarReq.getNumber(), LocalResourceConstant.EMERGENCY_ID), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "添加单兵应急", notes = "启动应急，单量单兵应急")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "addEmergencySoldierReq", required = true, dataType = "AddEmergencySoldierReq"),
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
    })
    @PutMapping("soldier/add")
    public BaseResponse mapEmergencySoldierAdd(@RequestBody AddEmergencySoldierReq addEmergencySoldierReq,
                                               @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("添加单兵应急--mapEmergencySoldierAdd");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {

            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(currentUserId, "用户不能为空 ");
                AssertUtil.isNotBlank(addEmergencySoldierReq.getNumber(), "单兵编号不能为空 ");
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.size() > 0, BizErrorCode.PARAM_ERROR, "当前未启动应急，不能操作");
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.containsKey(currentUserId), BizErrorCode.PARAM_ERROR, "您不是应急发起人，不能操作");
            }

            @Override
            public void doService() throws Exception {
                // 记录船舶应急资源
                emergencyService.emergencyStartUpdateMapSoldierResourceState(addEmergencySoldierReq.getNumber(), MapDataStatusEnums.G_SOLDIER_ONLINE_EMERGENCY.getType());

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.ADD_SOLIDER_MAP_EMERGENCY, addEmergencySoldierReq.getNumber(), LocalResourceConstant.EMERGENCY_ID), currentUserId);
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "移除单兵应急", notes = "移除单兵应急，单量单兵移除应急")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "removeEmergencyCarReq", required = true, dataType = "RemoveEmergencyCarReq"),
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
    })
    @PutMapping("soldier/remove")
    public BaseResponse mapEmergencySoldierRemove(@RequestBody RemoveEmergencySoldierReq removeEmergencySoldierReq,
                                                  @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("移除单兵应急--mapEmergencySoldierRemove");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {

            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(currentUserId, "用户不能为空");
                AssertUtil.isNotBlank(removeEmergencySoldierReq.getNumber(), "单兵编号号不存在");
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.size() > 0, BizErrorCode.PARAM_ERROR, "当前未启动应急，不能操作");
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.containsKey(currentUserId), BizErrorCode.PARAM_ERROR, "您不是应急发起人，不能操作");
            }

            @Override
            public void doService() throws Exception {
                // 记录船舶应急资源
                emergencyService.emergencyStartUpdateMapSoldierResourceState(removeEmergencySoldierReq.getNumber(), MapDataStatusEnums.G_SOLDIER_OFFLINE_EMERGENCY.getType());

                // 新建系统日志
                systemServiceFeignService.createSystemLog(
                        String.format(SystemLogConstant.REMOVE_SOLIDER_MAP_EMERGENCY, removeEmergencySoldierReq.getNumber(), LocalResourceConstant.EMERGENCY_ID), currentUserId);
                result.setSuccess(true);
            }
        });
    }


    @ApiOperation(value = "应急结束", notes = "应急结束，保存船舶、车辆、单兵应急数据、所有的船舶和车辆恢复在线状态数据,保存着火点信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mapEmergencyEndReq", required = true, dataType = "MapEmergencyEndReq"),
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
    })
    @PostMapping("end")
    public MapEmergencyEndRes mapEmergencyEnd(@RequestBody MapEmergencyEndReq mapEmergencyEndReq,
                                              @RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("应急结束--mapEmergencyEnd");
        final MapEmergencyEndRes result = new MapEmergencyEndRes();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {

            @Override
            public void check() throws Exception {
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.size() > 0, BizErrorCode.PARAM_ERROR, "当前未应急，不能操作");
                AssertUtil.isTrue(LocalResourceConstant.EMERGENCY.containsKey(currentUserId), BizErrorCode.PARAM_ERROR, "您不是应急发起人，不能操作");
            }

            @Override
            public void doService() throws Exception {
                Emergency localEmergency = LocalResourceConstant.EMERGENCY.get(currentUserId);
                // 结束应急，更新数据
                String emergencyEndName = mapEmergencyEndReq.getEmergencyEndName();
                if (StringUtils.isBlank(emergencyEndName)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    emergencyEndName = String.format(AppConstant.EMERGENCY_NAME, sdf.format(new Date()));
                }

                emergencyService.endEmergency(localEmergency.getId(), emergencyEndName);

                if (mapEmergencyEndReq.isClearTagging()) {
                    log.info("应急结束，清除应急数据");
                    mapTaggingService.clear();
                }
                result.setEmergencyId(LocalResourceConstant.EMERGENCY_ID);
                // 新建系统日志

                try {
                    Emergency emergency = emergencyService.queryEmergencyDetail(LocalResourceConstant.EMERGENCY_ID);
                    systemServiceFeignService.createSystemLog(
                            String.format(SystemLogConstant.MAP_EMERGENCY_END, emergencyEndName, emergency.getStartTime(), emergency.getEndTime(),
                                    localEmergency.getId()), currentUserId);
                } catch (Exception e) {
                }
                // 清除数据
                LocalResourceConstant.EMERGENCY.clear();
                LocalResourceConstant.EMERGENCY_ID = StringUtils.EMPTY;
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "应急列表", notes = "应急记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "emergencyLiReq", required = true, dataType = "EmergencyListReq")
    })
    @PostMapping("list")
    public EmergencyListRes emergencyList(@RequestBody EmergencyListReq emergencyLiReq) {
        log.info("应急列表--emergencyList");
        final EmergencyListRes result = new EmergencyListRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {


            }

            @Override
            public void doService() throws Exception {
                EmergencyListCondition emergencyListCondition = new EmergencyListCondition(emergencyLiReq.getCurrentPage(), emergencyLiReq.getPageSize());
                emergencyListCondition.setCreateDate(emergencyLiReq.getCreateDate());
                emergencyListCondition.setEndTime(emergencyLiReq.getEndTime());
                emergencyListCondition.setEmergencyName(emergencyLiReq.getEmergencyName());
                // 查询数据
                List<Emergency> emergencies = emergencyService.getEmergencyList(emergencyListCondition);
                result.setEmergencyInfos(EmergencyConvertor.emergenciesToEmergencyInfo(emergencies));
                result.setTotalRecords(emergencyService.getEmergencyListTotal(emergencyListCondition));
                result.setSuccess(true);
            }
        });
    }


    @ApiOperation(value = "查看当前是否正在应急", notes = "如果当前正在应急就不能再操作应急")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "emergencyLiReq", required = true, dataType = "EmergencyListReq"),
            @ApiImplicitParam(name = "current-user-id", paramType = "header", value = "由网关转换放入请求头中，可以不用填写")
    })
    @GetMapping("state")
    public GetEmergencyStateRes getEmergencyState(@RequestHeader(value = UserConstant.HEADER_CURRENT_USER_ID_KEY, required = false) String currentUserId) {
        log.info("查看当前是否正在应急--GetEmergencyStateRes");
        final GetEmergencyStateRes result = new GetEmergencyStateRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
            }

            @Override
            public void doService() throws Exception {

                if (null != LocalResourceConstant.EMERGENCY && LocalResourceConstant.EMERGENCY.size() > 0) {
                    result.setEmergency(true);
                    LocalResourceConstant.EMERGENCY.forEach((s, emergency) -> {
                        result.setStartTime(Long.valueOf(emergency.getStartTime()));
                        long currentTime = System.currentTimeMillis();
                        result.setEmergencyTime((currentTime - result.getStartTime()) / 1000);
                    });
                }
                // 查询数据
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "修改应急记录", notes = "修改应急记录数据")
    @PutMapping("info")
    public BaseResponse UpdateEmergencyRecord(@RequestBody UpdateEmergencyRecordReq updateEmergencyRecordReq) {
        log.info("修改应急记录--UpdateEmergencyRecord");
        final BaseResponse result = new BaseResponse();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(updateEmergencyRecordReq.getEmergencyName(), "应急名称不能为空");
                AssertUtil.isNotBlank(updateEmergencyRecordReq.getStartTime(), "应急开始时间不能为空");
                AssertUtil.isNotBlank(updateEmergencyRecordReq.getEndTime(), "应急结束时间不能为空");
                AssertUtil.isTrue(isValidDate(updateEmergencyRecordReq.getStartTime()),
                        BizErrorCode.PARAM_ERROR, "应急开始时间不是一个标准的时间格式");
                AssertUtil.isTrue(isValidDate(updateEmergencyRecordReq.getEndTime()),
                        BizErrorCode.PARAM_ERROR, "应急结束时间不是一个标准的时间格式");
            }

            @Override
            public void doService() throws Exception {
                Emergency emergency = new Emergency();
                emergency.setEmergencyName(updateEmergencyRecordReq.getEmergencyName());
                emergency.setStartTime(updateEmergencyRecordReq.getStartTime());
                emergency.setEndTime(updateEmergencyRecordReq.getEndTime());
                emergency.setId(updateEmergencyRecordReq.getId());

                emergencyService.updateEmergency(emergency);
                // 查询数据
                result.setSuccess(true);
            }
        });
    }

    @ApiOperation(value = "获取应急记录详情", notes = "获取应急记录详情")
    @GetMapping("detail")
    public GetEmergencyDetailRes getEmergencyDetail(@RequestParam String emergencyId) {
        log.info("获取应急详情--getEmergencyDetail");
        final GetEmergencyDetailRes result = new GetEmergencyDetailRes();
        return serviceExecuteTemplate.executeService(result, new ServiceCallBack() {
            @Override
            public void check() throws Exception {
                AssertUtil.isNotBlank(emergencyId, "应急编号为空");
            }

            @Override
            public void doService() throws Exception {

                List<EmergencyCar> emergencyCars = emergencyService.emergencyCarList(emergencyId);
                List<EmergencyCarInfo> emergencyCarInfos = new ArrayList<>();
                if (null != emergencyCars) {
                    emergencyCars.forEach(emergencyCar -> {
                        EmergencyCarInfo emergencyCarInfo = new EmergencyCarInfo();
                        emergencyCarInfo.setCarName(emergencyCar.getCarName());
                        emergencyCarInfo.setCarNumber(emergencyCar.getCarNumber());
                        emergencyCarInfos.add(emergencyCarInfo);
                    });
                }
                result.setEmergencyCarInfos(emergencyCarInfos);

                Emergency emergency = emergencyService.queryEmergencyDetail(emergencyId);
                if (null != emergency) {
                    result.setEmergencyName(emergency.getEmergencyName());
                    result.setEndTime(StringUtils.isNotBlank(emergency.getEndTime()) ?
                            StringUtils.substringBefore(emergency.getEndTime(), AppConstant.MYBATIS_DATA_TIME_SEPARATOR) : StringUtils.EMPTY);
                    result.setStartTime(StringUtils.isNotBlank(emergency.getStartTime()) ?
                            StringUtils.substringBefore(emergency.getStartTime(), AppConstant.MYBATIS_DATA_TIME_SEPARATOR) : StringUtils.EMPTY);
                }

                List<EmergencySoldier> emergencySoldiers = emergencyService.emergencySoldierList(emergencyId);
                List<EmergencySoldierInfo> emergencySoldierInfos = new ArrayList<>();
                if (null != emergencySoldiers) {
                    emergencySoldiers.forEach(emergencySoldier -> {
                        EmergencySoldierInfo emergencyCarInfo = new EmergencySoldierInfo();
                        emergencyCarInfo.setSoldierNumber(emergencySoldier.getSoldierNumber());
                        emergencyCarInfo.setPersonnelCompany(emergencySoldier.getPersonnelCompany());
                        emergencyCarInfo.setCallSign(emergencySoldier.getCallSign());
                        emergencyCarInfo.setEquipmentType(emergencySoldier.getEquipmentType());
                        emergencySoldierInfos.add(emergencyCarInfo);
                    });
                }
                result.setEmergencySoldierInfos(emergencySoldierInfos);

                List<EmergencyTagging> emergencyTaggings = emergencyService.emergencyTaggingList(emergencyId);
                List<EmergencyTaggingInfo> emergencyTaggingInfos = new ArrayList<>();
                if (null != emergencyTaggings) {
                    emergencyTaggings.forEach(emergencyTagging -> {
                        EmergencyTaggingInfo emergencyTaggingInfo = new EmergencyTaggingInfo();
                        emergencyTaggingInfo.setLongitude(emergencyTagging.getLongitude());
                        emergencyTaggingInfo.setLatitude(emergencyTagging.getLatitude());
                        emergencyTaggingInfo.setDescribe(emergencyTagging.getDescribe());
                        emergencyTaggingInfo.setTaggingType(emergencyTagging.getTaggingType());
                        MapTaggingEnums mapTaggingEnums = MapTaggingEnums.getMapTaggingEnumsByType(emergencyTagging.getTaggingType());
                        emergencyTaggingInfo.setTaggingTypeValue(null != mapTaggingEnums ? mapTaggingEnums.getDescribe() : StringUtils.EMPTY);
                        emergencyTaggingInfos.add(emergencyTaggingInfo);
                    });
                }
                result.setEmergencyTaggingInfos(emergencyTaggingInfos);
                // 查询数据
                result.setSuccess(true);
            }
        });
    }

    private static boolean isValidDate(String str) {
        boolean convertSuccess = true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }
}
